package edu.rmit.server;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.util.logging.Logger;

import edu.rmit.contant.ServerServiceConstant;
import edu.rmit.service.IServerService;
import edu.rmit.service.impl.ChatServiceImpl;
import edu.rmit.service.impl.GroupServiceImpl;
import edu.rmit.service.impl.MessageServiceImpl;
import edu.rmit.service.impl.SystemServiceImpl;
import edu.rmit.service.impl.UserServiceImpl;

public class Server {
	private int port = 1099;

	private String hostName = "127.0.0.1";

	private Logger log = Logger.getLogger(Server.class.getName());

	public Server() {
	}

	public Server(String hostName, int port) {
		this.port = port;
		this.hostName = hostName;
	}

	public void startServer() {
		try {
			LocateRegistry.createRegistry(port);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		IServerService serverService = null;
		try {
			serverService = new UserServiceImpl();
			registerServerService(serverService,
					ServerServiceConstant.USER_INFO_SERVICE);
			serverService = new SystemServiceImpl();
			registerServerService(serverService,
					ServerServiceConstant.SYSTEM_INFO_SERVICE);
			serverService = new GroupServiceImpl();
			registerServerService(serverService,
					ServerServiceConstant.GROUP_INFO_SERVICE);
			serverService = new ChatServiceImpl();
			registerServerService(serverService,
					ServerServiceConstant.CHAT_SERVER_SERVICE);
			
			serverService = new MessageServiceImpl();
			registerServerService(serverService,
					ServerServiceConstant.MESSAGE_INFO_SERVICE);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		
	}

	public void registerServerService(IServerService serverService,
			String serverServiceName) {
		String urlString = "//" + hostName + ":" + Integer.toString(port) + "/"
				+ serverServiceName;
		try {
			Naming.rebind(urlString, serverService);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		log.info("Bindings Finished " + serverServiceName
				+ ", waiting for client requests.");
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getHostName() {
		return hostName;
	}

	public void setHostName(String hostName) {
		this.hostName = hostName;
	}
}
